package br.com.mural.android.util;

import java.util.HashMap;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import br.com.mural.android.LoginActivity;
import br.com.mural.android.MainActivity;

public class GerenteSessao {
	SharedPreferences pref;
	Editor editor;
	Context _context;
	int PRIVATE_MODE = 0;
	
	private static final String PREF_NAME = "SessaoUsuario";
	private static final String IS_LOGIN = "IsLoggedIn";
	public static final String KEY_ID = "id";
	public static final String KEY_NOME = "nome";
	public static final String KEY_LOGIN = "login";
	public static final String KEY_SENHA = "senha";

	

	@SuppressLint("CommitPrefEdits")
	public GerenteSessao(Context context) {
		this._context = context;
		pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
		editor = pref.edit();
	}
	
	public void createLoginSession(int id, String nome, String login, String senha){
        editor.putBoolean(IS_LOGIN, true);
        
        editor.putInt(KEY_ID, id);
        editor.putString(KEY_NOME, nome);
        editor.putString(KEY_LOGIN, login);
        editor.putString(KEY_SENHA, senha);
         
        editor.commit();
    }
	
	public HashMap<String, String> getUserDetails(){
        HashMap<String, String> usuario = new HashMap<String, String>();
        
        usuario.put(KEY_ID, pref.getInt(KEY_ID, 0)+"");
        usuario.put(KEY_NOME, pref.getString(KEY_NOME, null));
        usuario.put(KEY_LOGIN, pref.getString(KEY_LOGIN, null));
        usuario.put(KEY_SENHA, pref.getString(KEY_SENHA, null)); 
        
        return usuario;
    }
	
	
	public void checkLogin(){
        if(!this.isLoggedIn()){
            Intent i = new Intent(_context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            _context.startActivity(i);
        }   
    }
	
	public void logoutUser(){
        editor.clear();
        editor.commit();
        Intent i = new Intent(_context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        _context.startActivity(i);  
    }

	public boolean isLoggedIn() {
		return pref.getBoolean(IS_LOGIN, false);
	}

}
